package com.gss.plugin.oauth2.config;

import com.gss.plugin.oauth2.handler.CustomAuth403Handler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import java.util.List;

/**
 * @author DYang
 * @date 2023/8/19
 */
@EnableGlobalMethodSecurity(
        securedEnabled = true, // 开启@Secure 注解授权
        prePostEnabled = true  // 开启前置和后置授权 @PreAuthorize
)
@EnableWebSecurity    // 启用security
@Configuration
public class SecurityConfig {

    @Autowired
    private Oauth2Properties oauth2Properties;
    @Autowired
    private CustomAuth403Handler customAuth403Handler;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PersistentTokenRepository persistentTokenRepository;
    @Autowired
    private AuthenticationConfiguration auth;

    /**
     * 密码加密
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     * 授权管理器
     * @return
     * @throws Exception
     */
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return auth.getAuthenticationManager();
    }


//    @Bean
//    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
//        // 关闭csrf 防护
//        http.csrf().disable();
//
//        // 登录控制
//        http
//                // 登录
//                .formLogin(
//                        form -> form
//                                // 当发现/login时发现是登录。必须和表单action一致
//                                .loginProcessingUrl("/login")
//                                // 登录成功处理器，不能和successForwardUrl 共存
//                                .successHandler(new CustomAuthSuccessHandler())
//                                // 登录失败处理器，不能和failureForwardUrl 共存
//                                .failureHandler(new CustomAuthFailHandler())
//                                .permitAll()
//                )
//                // 退出
//                .logout(
//                        logout -> logout
//                                .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll()
//                                .logoutSuccessUrl("/login").permitAll()
//
//                );
//
//        // 设置认证白名单
//        String[] whiteArr = this.getWhiteList();
//        if (whiteArr != null) {
//            // 允许被放过的请求和页面
//            http.authorizeRequests().antMatchers(whiteArr).permitAll();
//        }
//        // 自定义授权功能
//        http.authorizeRequests().anyRequest().access("@customAuthServiceImpl.hasPermission(request,authentication)");
//
//        // 异常处理
//        http.exceptionHandling()
//                // 授权失败处理
//                .accessDeniedHandler(customAuth403Handler);
//
//        // 记住我功能
//        if (oauth2Properties.isRememberMe()) {
//            http.rememberMe()
//                    // 记住我失效时间(s),默认2周
//                    .tokenValiditySeconds(oauth2Properties.getRememberMeTime())
//                    // 自定义登录逻辑
//                    .userDetailsService(userDetailsService)
//                    // 持久层对象
//                    .tokenRepository(persistentTokenRepository);
//        }
//
//        return http.build();
//    }

//    /**
//     * 允许所有人访问的白名单列表
//     * @return
//     */
//    private String[] getWhiteList() {
//        List<String> whitelist = oauth2Properties.getAuthWhitelist();
//        if (whitelist == null || whitelist.size() == 0) {
//            return null;
//        }
//        String[] arr = new String[whitelist.size()];
//        whitelist.toArray(arr);
//        return arr;
//    }


}
